package com.example.demo.controller;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.function.Consumer;

/**
 * @author Jerry
 * @date 2024-04-03 14:40
 */
public class SingLinkedList implements Iterable<Integer> {

    private Node head = null; //头指针


    private void remove(int index){
        Node prev = findNode(index - 1);
        assert prev != null;
        Node removed =  prev.next; // 被删除的节点
        prev.next = removed.next; // 上一个节点的下一个指针指向被删除节点的下一个节点
    }
    private void removeFirst(){
        head = head.next;
    }

    private void insertNode(int index, int value) {
        Node prev = findNode(index - 1);
        assert prev != null;
        prev.next = new Node(value, prev.next);
    }

    // 根据下标获取节点
    private Node findNode(int index) {
        int i = 0;
        for (Node p = head; p != null; p = p.next, i++) {
            if (i == index) {
                return p;
            }
        }
        return null;
    }



    private Node findLast() {
        if (head == null) return null;
        Node p;
        for (p = head; p.next != null; p = p.next) {
        }
        return p;
    }


    private void addLast(int value) {
        Node last = findLast();
        if (last == null) {
            addFirst(value);
            return;
        }
        last.next = new Node(value, null);
    }

    // 添加节点
    public void addFirst(int value) {
        //  链表为空的情况
        // head = new Node(value, null);
        // 链表不为空的情况
        head = new Node(value, head);
    }

    public void loop() {
        Node p = head;
        while (p != null) {
            System.out.println(p.value);
            p = p.next;
        }
    }

    public void loop(Consumer<Integer> consumer) {
        for (Node p = head; p != null; p = p.next) {
            consumer.accept(p.value);
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return new NodeIterator();
    }

    private class NodeIterator implements Iterator<Integer> {
        Node p = head;

        @Override
        public boolean hasNext() { // 是否有下一个元素
            return p != null;
        }

        @Override
        public Integer next() { // 返回当前元素，并指向下一个元素
            int v = p.value;
            p = p.next;
            return v;
        }
    }

    static class Node {
        int value; //值
        Node next; // 下一个节点类、

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }


}
